<template>
  <div class="dashboard-container">
    <!-- 欢迎区域 -->
    <el-row :gutter="24">
      <el-col :span="24">
        <div class="welcome-section">
          <div class="welcome-content">
            <div class="welcome-text">
              <h2>欢迎使用行易达系统</h2>
              <p>{{ currentDate }}</p>
            </div>
            <div class="system-status">
              <div class="status-item">
                <i class="el-icon-cpu"></i>
                <span>CPU: {{ systemInfo.cpuUsage }}</span>
              </div>
              <div class="status-item">
                <i class="el-icon-monitor"></i>
                <span>内存: {{ systemInfo.memoryUsage }}</span>
              </div>
              <div class="status-item">
                <i class="el-icon-time"></i>
                <span>运行: {{ systemInfo.uptime }}</span>
              </div>
            </div>
          </div>
        </div>
      </el-col>
    </el-row>

    <!-- 快捷功能区 -->
    <el-row :gutter="24" class="feature-section">
      <el-col :xs="24" :sm="8" v-for="(item, index) in quickAccess" :key="index">
        <div class="feature-card" @click="handleQuickAccess(item.route)">
          <i :class="item.icon"></i>
          <div class="feature-info">
            <h3>{{ item.title }}</h3>
            <p>{{ item.desc }}</p>
          </div>
        </div>
      </el-col>
    </el-row>

    <!-- 系统信息 -->
    <el-row :gutter="24">
      <el-col :span="24">
        <div class="system-section">
          <div class="section-header">
            <h3>系统信息</h3>
          </div>
          <el-row :gutter="24" class="system-info">
            <el-col :xs="24" :sm="12">
              <div class="info-group">
                <div class="info-item">
                  <span class="info-label">操作系统</span>
                  <span class="info-value">{{ systemInfo.osInfo }}</span>
                </div>
                <div class="info-item">
                  <span class="info-label">CPU核心</span>
                  <span class="info-value">{{ systemInfo.cpuCores }}</span>
                </div>
                <div class="info-item">
                  <span class="info-label">JVM线程</span>
                  <span class="info-value">{{ systemInfo.jvmThreads }}</span>
                </div>
              </div>
            </el-col>
            <el-col :xs="24" :sm="12">
              <div class="info-group">
                <div class="info-item">
                  <span class="info-label">内存使用</span>
                  <span class="info-value">{{ systemInfo.memoryUsage }}</span>
                </div>
                <div class="info-item">
                  <span class="info-label">JVM堆内存</span>
                  <span class="info-value">{{ systemInfo.jvmHeap }}</span>
                </div>
                <div class="info-item">
                  <span class="info-label">磁盘使用</span>
                  <span class="info-value">{{ systemInfo.diskUsage }}</span>
                </div>
              </div>
            </el-col>
          </el-row>
        </div>
      </el-col>
    </el-row>

    <!-- 监控图表 -->
    <el-row :gutter="24">
      <el-col :xs="24" :sm="12">
        <div class="chart-card">
          <div class="chart-header">
            <h3>CPU负载监控</h3>
            <el-tag size="small" effect="dark" type="success">实时</el-tag>
          </div>
          <div class="chart-content">
            <div ref="cpuChart" style="height: 300px;"></div>
          </div>
        </div>
      </el-col>
      <el-col :xs="24" :sm="12">
        <div class="chart-card">
          <div class="chart-header">
            <h3>内存使用趋势</h3>
            <el-tag size="small" effect="dark" type="warning">实时</el-tag>
          </div>
          <div class="chart-content">
            <div ref="memoryChart" style="height: 300px;"></div>
          </div>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { getSystemInfo } from '@/api/system/system'
import * as echarts from 'echarts'

export default {
  name: 'Dashboard',
  data() {
    return {
      currentDate: '',
      userName: '访客',
      userAvatar: '',
      quickAccess: [
        {
          title: '业务管理',
          desc: '管理业务相关信息',
          icon: 'el-icon-s-management',
          route: '/business/daily-train-ticket'
        },
        {
          title: '基础数据',
          desc: '维护系统基础数据',
          icon: 'el-icon-s-data',
          route: '/base/station'
        },
        {
          title: '订单管理',
          desc: '查看和管理订单信息',
          icon: 'el-icon-s-order',
          route: '/dafa/confirm-order'
        }
      ],
      systemInfo: {
        osInfo: '',
        cpuUsage: '',
        cpuCores: '',
        jvmThreads: '',
        memoryUsage: '',
        jvmHeap: '',
        diskUsage: '',
        uptime: ''
      },
      cpuChart: null,
      memoryChart: null,
      timer: null
    }
  },
  created() {
    this.initCurrentDate()
    this.getUserInfo()
    this.getSystemInfo()
  },
  mounted() {
    this.initCharts()
    // 定时刷新数据
    this.timer = setInterval(() => {
      this.updateCharts()
    }, 5000)
  },
  beforeDestroy() {
    if (this.timer) {
      clearInterval(this.timer)
    }
    // 销毁图表实例
    if (this.cpuChart) {
      this.cpuChart.dispose()
    }
    if (this.memoryChart) {
      this.memoryChart.dispose()
    }
  },
  methods: {
    initCurrentDate() {
      const now = new Date()
      const year = now.getFullYear()
      const month = now.getMonth() + 1
      const date = now.getDate()
      const week = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'][now.getDay()]
      this.currentDate = `${year}年${month}月${date}日 ${week}`
    },
    getUserInfo() {
      // 从vuex或接口获取用户信息
      // this.userName = 实际用户名
      // this.userAvatar = 实际头像地址
    },
    async getSystemInfo() {
      try {
        const response = await getSystemInfo()
        if (response.code === 200) {
          const data = response.data
          this.systemInfo = {
            osInfo: data.osInfo || '未知',
            cpuUsage: data.cpuUsage || '0%',
            cpuCores: data.cpuCores || '未知',
            jvmThreads: data.jvmThreads ? `${data.jvmThreads}个` : '未知',
            memoryUsage: data.memoryUsage || '未知',
            jvmHeap: data.jvmHeap || '未知',
            diskUsage: data.diskUsage || '未知',
            uptime: data.uptime || '未知'
          }
        }
        console.log('获取系统信息成功:', response)
      } catch (error) {
        console.error('获取系统信息失败:', error)
        this.$message.error('获取系统信息失败，请稍后重试')
      }
    },
    handleQuickAccess(route) {
      try {
        const hasPermission = true; // 这里可以添加实际的权限检查逻辑

        if (hasPermission) {
          this.$router.push(route).catch(err => {
            if (err.name !== 'NavigationDuplicated') {
              console.error('路由跳转失败:', err);
              this.$message.error('页面跳转失败，请稍后重试');
            }
          });
        } else {
          this.$message.warning('您没有访问该页面的权限');
        }
      } catch (error) {
        console.error('路由跳转失败:', error);
        this.$message.error('页面跳转失败，请稍后重试');
      }
    },
    initCharts() {
      // 初始化CPU使用率图表
      this.cpuChart = echarts.init(this.$refs.cpuChart)
      this.cpuChart.setOption({
        title: {
          text: 'CPU使用率',
          left: 'center',
          top: 10
        },
        tooltip: {
          trigger: 'axis',
          formatter: '{b}<br/>{c}%'
        },
        grid: {
          top: '15%',
          left: '3%',
          right: '4%',
          bottom: '8%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: this.getTimePoints(),
          axisLabel: {
            interval: 2,
            fontSize: 10
          }
        },
        yAxis: {
          type: 'value',
          max: 100,
          min: 0,
          splitNumber: 5,
          axisLabel: {
            formatter: '{value}%'
          }
        },
        series: [{
          data: this.generateRandomData(),
          type: 'line',
          smooth: true,
          symbol: 'none',
          areaStyle: {
            opacity: 0.2,
            color: '#409EFF'
          },
          lineStyle: {
            width: 2,
            color: '#409EFF'
          }
        }]
      })

      // 初始化内存使用图表
      this.memoryChart = echarts.init(this.$refs.memoryChart)
      this.memoryChart.setOption({
        title: {
          text: '内存使用率',
          left: 'center',
          top: 10
        },
        tooltip: {
          trigger: 'axis',
          formatter: '{b}<br/>{c}%'
        },
        grid: {
          top: '15%',
          left: '3%',
          right: '4%',
          bottom: '8%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: this.getTimePoints(),
          axisLabel: {
            interval: 2,
            fontSize: 10
          }
        },
        yAxis: {
          type: 'value',
          max: 100,
          min: 0,
          splitNumber: 5,
          axisLabel: {
            formatter: '{value}%'
          }
        },
        series: [{
          data: this.generateRandomData(),
          type: 'line',
          smooth: true,
          symbol: 'none',
          areaStyle: {
            opacity: 0.2,
            color: '#67C23A'
          },
          lineStyle: {
            width: 2,
            color: '#67C23A'
          }
        }]
      })
    },
    updateCharts() {
      const cpuData = this.generateRandomData()
      const memoryData = this.generateRandomData()

      this.cpuChart.setOption({
        xAxis: {
          data: this.getTimePoints()
        },
        series: [{
          data: cpuData
        }]
      })

      this.memoryChart.setOption({
        xAxis: {
          data: this.getTimePoints()
        },
        series: [{
          data: memoryData
        }]
      })
    },
    getTimePoints() {
      const points = []
      const now = new Date()
      for (let i = 10; i >= 0; i--) {
        const time = new Date(now - i * 5000)
        points.push(time.getMinutes().toString().padStart(2, '0') + ':' +
          time.getSeconds().toString().padStart(2, '0'))
      }
      return points
    },
    generateRandomData() {
      return Array.from({ length: 11 }, () =>
        Math.floor(Math.random() * 40 + 30))
    }
  }
}
</script>

<style scoped>
.dashboard-container {
  padding: 24px;
  background-color: #f6f8fa;
  min-height: calc(100vh - 84px);
}

.welcome-section {
  background: linear-gradient(135deg, #1890ff 0%, #36cfc9 100%);
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  margin-bottom: 24px;
  overflow: hidden;
}

.welcome-content {
  padding: 32px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: white;
}

.welcome-text h2 {
  margin: 0;
  font-size: 28px;
  font-weight: 500;
  letter-spacing: 0.5px;
}

.welcome-text p {
  margin: 8px 0 0;
  font-size: 16px;
  opacity: 0.9;
}

.system-status {
  display: flex;
  gap: 24px;
}

.status-item {
  display: flex;
  align-items: center;
  gap: 8px;
  background: rgba(255, 255, 255, 0.1);
  padding: 8px 16px;
  border-radius: 8px;
}

.status-item i {
  font-size: 20px;
}

.feature-section {
  margin-bottom: 24px;
}

.feature-card {
  background: white;
  padding: 24px;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 16px;
  margin-bottom: 24px;
}

.feature-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.08);
}

.feature-card i {
  font-size: 32px;
  color: #1890ff;
}

.feature-info h3 {
  margin: 0;
  font-size: 18px;
  color: #1f2329;
}

.feature-info p {
  margin: 4px 0 0;
  font-size: 14px;
  color: #86909c;
}

.system-section {
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  padding: 24px;
  margin-bottom: 24px;
}

.section-header {
  margin-bottom: 24px;
  border-bottom: 1px solid #f0f0f0;
  padding-bottom: 16px;
}

.section-header h3 {
  margin: 0;
  font-size: 20px;
  color: #1f2329;
  font-weight: 500;
}

.info-group {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.info-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  background: #f6f8fa;
  border-radius: 8px;
}

.info-label {
  color: #4e5969;
  font-size: 14px;
}

.info-value {
  color: #1f2329;
  font-weight: 500;
}

.chart-card {
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  padding: 24px;
  margin-bottom: 24px;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.chart-header h3 {
  margin: 0;
  font-size: 18px;
  color: #1f2329;
  font-weight: 500;
}

.chart-content {
  background: #f6f8fa;
  border-radius: 8px;
  padding: 16px;
}

@media (max-width: 768px) {
  .dashboard-container {
    padding: 16px;
  }

  .welcome-content {
    flex-direction: column;
    text-align: center;
    padding: 24px;
  }

  .system-status {
    flex-direction: column;
    margin-top: 16px;
    width: 100%;
  }

  .status-item {
    justify-content: center;
  }

  .feature-card {
    flex-direction: column;
    text-align: center;
    padding: 20px;
  }

  .info-group {
    margin-bottom: 16px;
  }
}
</style>

